<template>
  <div id="order">
    <div class="order-top">
      <div class="form-group">
        <span class="spanRed">*</span>供应商1：
        <el-input
          style="width: 150px"
          v-model="priceComparison.pro1Name"
        ></el-input>
        <el-button @click="getPro(1)">...</el-button>
      </div>
      <div class="form-group">
        <span class="spanRed">*</span>供应商2：
        <el-input
          style="width: 150px"
          v-model="priceComparison.pro2Name"
        ></el-input>
        <el-button @click="getPro(2)">...</el-button>
      </div>
      <div class="form-group">
        <span class="spanRed">*</span>供应商3：
        <el-input
          style="width: 150px"
          v-model="priceComparison.pro3Name"
        ></el-input>
        <el-button @click="getPro(3)">...</el-button>
      </div>

      <div class="form-group">
        <span class="demonstration">单据日期:</span>
        <el-date-picker
          v-model="priceComparison.createDate"
          align="right"
          type="date"
          placeholder="选择日期"
          style="margin-left: 10px"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
        >
        </el-date-picker>
      </div>

      <div class="form-group">
        业务员：
        <el-select
          v-model="priceComparison.yid"
          placeholder="业务员"
          style="margin-left: 10px; width: 100px"
        >
          <el-option label="(空)" :value="0"> </el-option>
          <el-option
            v-for="item in employee"
            :key="item.employeeId"
            :label="item.employeeName"
            :value="item.employeeId"
          >
          </el-option>
        </el-select>
      </div>

      <div class="form-group">
        <i class="el-icon-paperclip" style="color: blue"></i>
        <span style="color: blue">上传附件</span>
        <span style="margin-left: 10px">单据编号:</span>
        <el-input
          style="width: 120px; margin-left: 10px; margin-right: 20px"
          placeholder=""
          v-model="priceComparison.documentNumber"
          clearable
        >
        </el-input>
        <el-dropdown>
          <span class="el-dropdown-link">
            <i class="el-icon-edit"></i>
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item>CGBJ</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </div>

    <el-dialog title="商品库存查询" :visible.sync="dialogVisible3" width="30%">
      <div class="dialog-footer">
        <el-button type="primary" @click="dialogVisible3 = false"
          >确认</el-button
        >
        <el-button @click="dialogVisible3 = false">关闭</el-button>
      </div>
    </el-dialog>

    <el-divider></el-divider>
    <div style="float: right; margin-bottom: 10px">
      <!-- <el-button type="primary">保存并新增</el-button> -->
      <el-button type="primary" @click="save()"
        >保存{{ this.priceComparison.id ? "修改" : "新增" }}</el-button
      >
      <el-button type="primary">导入</el-button>
    </div>

    <div class="order-content">
      <el-table
        :data="priComDetail"
        :row-style="{ height: '55px' }"
        border
        style="width: 100%; font-size: 13px; margin-left: 20px"
        show-summary
        :summary-method="getSummaries"
        height="330px"
      >
        <el-table-column style="width: 120px; padding-left: 10px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              style="margin-left: 10px"
              @click="addRow(scope.$index)"
              ><i class="el-icon-circle-plus-outline"></i
            ></el-button>
            <el-button size="mini" @click="reduceRow(scope.$index)"
              ><i class="el-icon-remove-outline"></i
            ></el-button>
          </template>
        </el-table-column>

        <el-table-column prop="goodcode" label="商品编号" width="300">
          <template slot="header" slot-scope="{ column }">
            <span class="spanRed">*</span> {{ column.label }}
          </template>
          <template slot-scope="scope">
            <el-input
              style="width: 200px"
              placeholder="商品"
              v-model="scope.row.goodcode"
            ></el-input
            ><el-button @click="goods(scope.$index)">选择</el-button>
          </template>
        </el-table-column>

        <el-table-column prop="goodname" label="商品名称" width="150">
          <template slot-scope="scope">
            <el-input size="small" v-model="scope.row.goodname"></el-input>
          </template>
        </el-table-column>

        <el-table-column prop="imagename" label="商品图片" width="120">
        </el-table-column>

        <el-table-column
          :label="'供应商1 ' + priceComparison.pro1Name"
          width="120"
        >
          <el-table-column prop="purchasePrice1" label="购货单价" width="130">
            <template slot-scope="scope">
              <el-input
                style="width: 100px"
                placeholder="购货单价"
                v-model="scope.row.purchasePrice1"
                @blur="calculateRow1(scope.row)"
              ></el-input>
            </template>
          </el-table-column>

          <!-- 折扣率 -->
          <el-table-column prop="discount1" label="折扣率(%)" width="120">
            <template slot-scope="scope">
              <el-input
                style="width: 90px"
                placeholder="折扣率"
                v-model="scope.row.discount1"
                @blur="calculateRow1(scope.row)"
              ></el-input>
            </template>
          </el-table-column>

          <!-- 税率 -->
          <el-table-column prop="taxRate1" label="税率(%)" width="120">
            <template slot-scope="scope">
              <el-input
                style="width: 90px"
                placeholder="税率"
                v-model="scope.row.taxRate1"
                @blur="calculateRow1(scope.row)"
              ></el-input>
            </template>
          </el-table-column>

          <!-- 价税合计 -->
          <el-table-column prop="totalMoney1" label="价税合计" width="120">
            <template slot-scope="scope">
              <el-input
                style="width: 90px"
                placeholder="价税合计"
                v-model="scope.row.totalMoney1"
                @blur="calculateRowTotalMoney1(scope.row)"
              ></el-input>
            </template>
          </el-table-column>

          <el-table-column label="选择供应商" width="120">
            <template slot-scope="scope">
              <el-radio v-model="scope.row.radio" label="1">选择</el-radio>
            </template>
          </el-table-column>
        </el-table-column>

        <el-table-column
          :label="'供应商2 ' + priceComparison.pro2Name"
          width="120"
        >
          <el-table-column prop="purchasePrice2" label="购货单价" width="130">
            <template slot-scope="scope">
              <el-input
                style="width: 100px"
                placeholder="购货单价"
                v-model="scope.row.purchasePrice2"
                @blur="calculateRow2(scope.row)"
              ></el-input>
            </template>
          </el-table-column>

          <!-- 折扣率 -->
          <el-table-column prop="discount2" label="折扣率(%)" width="120">
            <template slot-scope="scope">
              <el-input
                style="width: 90px"
                placeholder="折扣率"
                v-model="scope.row.discount2"
                @blur="calculateRow2(scope.row)"
              ></el-input>
            </template>
          </el-table-column>

          <!-- 税率 -->
          <el-table-column prop="taxRate2" label="税率(%)" width="120">
            <template slot-scope="scope">
              <el-input
                style="width: 90px"
                placeholder="税率"
                v-model="scope.row.taxRate2"
                @blur="calculateRow2(scope.row)"
              ></el-input>
            </template>
          </el-table-column>

          <!-- 价税合计 -->
          <el-table-column prop="totalMoney2" label="价税合计" width="120">
            <template slot-scope="scope">
              <el-input
                style="width: 90px"
                placeholder="价税合计"
                v-model="scope.row.totalMoney2"
                @blur="calculateRowTotalMoney2(scope.row)"
              ></el-input>
            </template>
          </el-table-column>

          <el-table-column label="选择供应商" width="120">
            <template slot-scope="scope">
              <el-radio v-model="scope.row.radio" label="2">选择</el-radio>
            </template>
          </el-table-column>
        </el-table-column>

        <el-table-column
          :label="'供应商3 ' + priceComparison.pro3Name"
          width="120"
        >
          <el-table-column prop="purchasePrice3" label="购货单价" width="130">
            <template slot-scope="scope">
              <el-input
                style="width: 100px"
                placeholder="购货单价"
                v-model="scope.row.purchasePrice3"
                @blur="calculateRow3(scope.row)"
              ></el-input>
            </template>
          </el-table-column>

          <!-- 折扣率 -->
          <el-table-column prop="discount3" label="折扣率(%)" width="120">
            <template slot-scope="scope">
              <el-input
                style="width: 90px"
                placeholder="折扣率"
                v-model="scope.row.discount3"
                @blur="calculateRow3(scope.row)"
              ></el-input>
            </template>
          </el-table-column>

          <!-- 税率 -->
          <el-table-column prop="taxRate3" label="税率(%)" width="120">
            <template slot-scope="scope">
              <el-input
                style="width: 90px"
                placeholder="税率"
                v-model="scope.row.taxRate3"
                @blur="calculateRow3(scope.row)"
              ></el-input>
            </template>
          </el-table-column>

          <!-- 价税合计 -->
          <el-table-column prop="totalMoney3" label="价税合计" width="120">
            <template slot-scope="scope">
              <el-input
                style="width: 90px"
                placeholder="价税合计"
                v-model="scope.row.totalMoney3"
                @blur="calculateRowTotalMoney3(scope.row)"
              ></el-input>
            </template>
          </el-table-column>
        </el-table-column>

        <el-table-column prop="categoryName" label="商品类别" width="120">
        </el-table-column>
        <el-table-column prop="brandName" label="品牌" width="120">
        </el-table-column>
        <el-table-column prop="unitname" label="单位" width="120">
        </el-table-column>

        <!-- 仓库 -->
        <el-table-column prop="" label="仓库" width="320">
          <template slot="header" slot-scope="{ column }">
            <span class="spanRed">*</span> {{ column.label }}
          </template>
          <template slot-scope="scope">
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="dialogVisible3 = true"
            ></el-button>

            <el-select v-model="scope.row.wId" placeholder="请选择">
              <el-option
                v-for="item in storeHouse"
                :key="item.shId"
                :label="item.storeHomeCode + ' ' + item.storeHomeName"
                :value="item.shId"
              >
              </el-option>
            </el-select>
          </template>
        </el-table-column>

        <!-- 可用库存 -->
        <el-table-column prop="availableStock" label="可用库存" width="120">
          <template slot-scope="scope">
            {{ scope.row.availableStock }}
          </template>
        </el-table-column>

        <!-- 仓库结束 -->

        <!-- 数量 -->
        <el-table-column prop="totalNum" label="数量" width="130">
          <template slot="header" slot-scope="{ column }">
            <span class="spanRed">*</span> {{ column.label }}
          </template>
          <template slot-scope="scope">
            <el-input
              style="width: 100px"
              placeholder="数量"
              v-model="scope.row.totalNum"
              @blur="calculateRowAll(scope.row)"
            ></el-input>
          </template>
        </el-table-column>

        <!-- 整件散包 -->
        <el-table-column prop="packType" label="整件散包" width="120">
        </el-table-column>

        <!-- 基本单位 -->
        <el-table-column prop="unitname" label="基本单位" width="120">
        </el-table-column>

        <!-- 基本数量 -->
        <el-table-column prop="totalNum" label="基本数量" width="120">
          <template slot-scope="scope">
            {{ scope.row.totalNum }}
          </template>
        </el-table-column>

        <!-- 备注 -->
        <el-table-column label="备注" width="120">
          <template slot-scope="scope">
            <el-input
              style="width: 90px"
              placeholder="备注"
              v-model="scope.row.detailRemark"
            ></el-input>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div>
      <el-input
        type="textarea"
        placeholder="备注"
        rows="2"
        v-model="priceComparison.remark"
        style="width: 100%; margin: 10px 0 0 10px"
      >
      </el-input>
    </div>

    <div style="float: right; margin-top: 10px">
      <el-button @click="goto('priceComDoc')">历史单据</el-button>
    </div>

    <el-dialog top="20px" title="选择供应商" :visible.sync="dialogShow">
      <ProviderChoose ref="choosePro" :dialogShow="dialogShow" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogShow = false">取 消</el-button>
        <el-button type="primary" @click="yes">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog top="20px" title="选择商品" :visible.sync="goodsShow">
      <GoodsChoose ref="chooseGoods" :goodsShow="goodsShow" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="goodsShow = false">取 消</el-button>
        <el-button type="primary" @click="yesGoods">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>



<script>
import ProviderChoose from "../public_com/ProviderChoose.vue";
import GoodsChoose from "../public_com/GoodsChoose.vue";

export default {
  name: "priceComparison",
  components: {
    ProviderChoose,
    GoodsChoose,
  },
  data() {
    return {
      index: "",
      goodsShow: false,
      dialogVisible3: false,
      dialogShow: false, //供应商弹窗
      employee: [], //页务员
      storeHouse: [], //仓库
      flagPro: "", //标志哪个供应商
      jsonObject:[],
      priceComparison: {
        //其它
        pro1Name: "",
        pro2Name: "",
        pro3Name: "",
        //数据库属性
        id: "",
        pro1Id: "",
        pro2Id: "",
        pro3Id: "",
        createDate: "",
        yid: "",
        quantity: "", //数量
        amount1: "", //供应商1总金额
        amount2: "", //供应商2总金额
        amount3: "", //供应商3总金额
        remark: "",
        documentNumber: "",
      }, //比价单详情
      priComDetail: [
        {
          goodcode: "",
          goodname: "",
          purchasePrice1: 0,
          discount1: 0,
          taxRate1: 0,
          totalMoney1: 0,
          purchasePrice2: 0,
          discount2: 0,
          taxRate2: 0,
          totalMoney2: 0,
          purchasePrice3: 0,
          discount3: 0,
          taxRate3: 0,
          totalMoney3: 0,
          radio: "",
          categoryName: "",
          brandName: "",
          unitname: "",
          imagename: "",
          availableStock: "",
          wId: "",
          totalNum: 1,
          packType: "",
          detailRemark: "",
        },
      ],
    };
  },
  methods: {
    goto(to) {
      this.$router.push(to);
    },
    successMessage(msg) {
      this.$message({
        message: msg,
        type: "success",
      });
    },
    errorMessage(msg) {
      this.$message({
        message: msg,
        type: "error",
      });
    },
    save() {
      //数据校验
      // 校验供应商
      if (
        !this.priceComparison.pro1Id ||
        !this.priceComparison.pro2Id ||
        !this.priceComparison.pro3Id
      ) {
        this.errorMessage("供应商不能为空");
        return;
      }

      if (
        this.priceComparison.pro1Id == this.priceComparison.pro2Id ||
        this.priceComparison.pro1Id == this.priceComparison.pro3Id ||
        this.priceComparison.pro2Id == this.priceComparison.pro3Id
      ) {
        this.errorMessage("供应商不能重复");
        return;
      }

      // 校验单据日期
      if (!this.priceComparison.createDate) {
        this.errorMessage("单据日期不能为空");
        return;
      }

      var msgWId = "";

      console.log(this.priceComparison);
      //获取入库单明细
      var details = [];

      this.priComDetail.forEach((priCom, index) => {
        if (priCom.goodcode && priCom.goodname) {
          // 只有当商品编码不为空时，才添加到details

          if (!priCom.wId) {
            msgWId = "商品" + priCom.goodcode + "仓库不可以为空";
            return;
          }

          details.push({
            goodcode: priCom.goodcode,
            goodname: priCom.goodname,
            purchasePrice1: priCom.purchasePrice1,
            discount1: priCom.discount1,
            taxRate1: priCom.taxRate1,
            totalMoney1: priCom.totalMoney1,
            purchasePrice2: priCom.purchasePrice2,
            discount2: priCom.discount2,
            taxRate2: priCom.taxRate2,
            totalMoney2: priCom.totalMoney2,
            purchasePrice3: priCom.purchasePrice3,
            discount3: priCom.discount3,
            taxRate3: priCom.taxRate3,
            totalMoney3: priCom.totalMoney3,
            radio: priCom.radio,
            unitname: priCom.unitname,
            wId: priCom.wId,
            totalNum: priCom.totalNum,
            detailRemark: priCom.detailRemark,
          });
        }
      });

      if (msgWId) {
        this.errorMessage(msgWId);
        return;
      }

      if (details.length < 1) {
        this.errorMessage("商品信息不可以为空");
        return;
      }

      // console.log(details)
      const formdata = new FormData();
      formdata.append("priceComparison", JSON.stringify(this.priceComparison));
      formdata.append("priComDetail", JSON.stringify(details));

      if (!this.priceComparison.id) {
        this.axios
          .post("/purchase/priceComparison/add", formdata)
          .then((rs) => {
            if ((rs.data.code = 200)) {
              this.successMessage("添加成功");
              this.letNull();
            } else {
              this.errorMessage("添加失败");
            }
          });
      } else {
        this.axios.post("/purchase/priceComparison/up", formdata).then((rs) => {
          if ((rs.data.code = 200)) {
            this.successMessage("修改成功");
            this.letNull();
          } else {
            this.errorMessage("修改失败");
          }
        });
      }
    },
    letNull() {
      this.priceComparison = {
        pro1Name: "",
        pro2Name: "",
        pro3Name: "",
        //数据库属性
        id: "",
        pro1Id: "",
        pro2Id: "",
        pro3Id: "",
        createDate: "",
        yid: "",
        quantity: "", //数量
        amount1: "", //供应商1总金额
        amount2: "", //供应商2总金额
        amount3: "", //供应商3总金额
        remark: "",
        documentNumber: "",
      };
      this.priComDetail = [
        {
          goodcode: "",
          goodname: "",
          purchasePrice1: 0,
          discount1: 0,
          taxRate1: 0,
          totalMoney1: 0,
          purchasePrice2: 0,
          discount2: 0,
          taxRate2: 0,
          totalMoney2: 0,
          purchasePrice3: 0,
          discount3: 0,
          taxRate3: 0,
          totalMoney3: 0,
          radio: "",
          categoryName: "",
          brandName: "",
          unitname: "",
          imagename: "",
          availableStock: "",
          wId: "",
          totalNum: 1,
          packType: "",
        },
      ];
    },
    yesGoods() {
      this.goodsShow = false;
      var selectedGoods = this.$refs.chooseGoods.selectionList;
      if (selectedGoods.length > 0 && this.index !== "") {
        var currentIndex = parseInt(this.index);
        // 插入第一条数据到指定的currentIndex行
        Object.keys(selectedGoods[0]).forEach((key) => {
          this.$set(
            this.priComDetail[currentIndex],
            key,
            selectedGoods[0][key]
          );
        });

        // 处理剩余的数据
        for (let i = 1; i < selectedGoods.length; i++) {
          // 在当前行后新增一行
          this.addRow(currentIndex + i - 1);

          // 插入数据到新增的行
          Object.keys(selectedGoods[i]).forEach((key) => {
            this.$set(
              this.priComDetail[currentIndex + i],
              key,
              selectedGoods[i][key]
            );
          });
        }
      }
    },
    calculateRowAll(row) {
      const positiveIntegerRegex = /^\d+$/; // 匹配正整数

      // 验证和重置数量
      if (
        !positiveIntegerRegex.test(row.totalNum) ||
        row.totalNum === "" ||
        row.totalNum == 0
      ) {
        this.$message({
          showClose: true,
          message: "数量必须是正整数",
          type: "warning",
        });

        // 将字符串转换为浮点数
        let discountValue = parseFloat(row.totalNum);

        // 如果isNaN，则设置为0
        if (isNaN(discountValue)) {
          row.totalNum = 1;
        } else {
          // 修正为0-100之间的值
          if (discountValue <= 0) {
            row.totalNum = 1;
          } else {
            // 四舍五入到两位小数
            row.totalNum = parseFloat(discountValue.toFixed(0));
          }
        }
      }

      this.calculateRow1(row);
      this.calculateRow2(row);
      this.calculateRow3(row);
    },
    calculateRowTotalMoney3(row) {
      //价税合计
      // 使用正则表达式验证输入值是否为有效的正整数
      const positiveNumberRegex = /^\d+(\.\d{1,2})?$/; // 匹配正数，小数点最多两位
      // 验证和重置价税合计（假设价税合计可以是浮点数）
      if (
        !positiveNumberRegex.test(row.totalMoney3) ||
        row.totalMoney3 === ""
      ) {
        this.$message({
          showClose: true,
          message: "价税合计必须是正数,且小数点后最多两位",
          type: "warning",
        });
        // 将字符串转换为浮点数
        let discountValue = parseFloat(row.totalMoney3);

        // 如果isNaN，则设置为0
        if (isNaN(discountValue)) {
          row.totalMoney3 = 0;
        } else {
          if (discountValue < 0) {
            row.totalMoney3 = 0;
          } else {
            // 四舍五入到两位小数
            row.totalMoney3 = parseFloat(discountValue.toFixed(2));
          }
        }
      }

      row.purchasePrice3 = (
        row.totalMoney3 /
        (1 + row.taxRate3 / 100) /
        row.totalNum /
        (1 - row.discount3 / 100)
      ).toFixed(2);

      this.calculateRow3(row);
    },
    calculateRowTotalMoney2(row) {
      //价税合计
      // 使用正则表达式验证输入值是否为有效的正整数
      const positiveNumberRegex = /^\d+(\.\d{1,2})?$/; // 匹配正数，小数点最多两位
      // 验证和重置价税合计（假设价税合计可以是浮点数）
      if (
        !positiveNumberRegex.test(row.totalMoney2) ||
        row.totalMoney2 === ""
      ) {
        this.$message({
          showClose: true,
          message: "价税合计必须是正数,且小数点后最多两位",
          type: "warning",
        });
        // 将字符串转换为浮点数
        let discountValue = parseFloat(row.totalMoney2);

        // 如果isNaN，则设置为0
        if (isNaN(discountValue)) {
          row.totalMoney2 = 0;
        } else {
          if (discountValue < 0) {
            row.totalMoney2 = 0;
          } else {
            // 四舍五入到两位小数
            row.totalMoney2 = parseFloat(discountValue.toFixed(2));
          }
        }
      }

      row.purchasePrice2 = (
        row.totalMoney2 /
        (1 + row.taxRate2 / 100) /
        row.totalNum /
        (1 - row.discount2 / 100)
      ).toFixed(2);

      this.calculateRow2(row);
    },
    calculateRowTotalMoney1(row) {
      //价税合计
      // 使用正则表达式验证输入值是否为有效的正整数
      const positiveNumberRegex = /^\d+(\.\d{1,2})?$/; // 匹配正数，小数点最多两位
      // 验证和重置价税合计（假设价税合计可以是浮点数）
      if (
        !positiveNumberRegex.test(row.totalMoney1) ||
        row.totalMoney1 === ""
      ) {
        this.$message({
          showClose: true,
          message: "价税合计必须是正数,且小数点后最多两位",
          type: "warning",
        });
        // 将字符串转换为浮点数
        let discountValue = parseFloat(row.totalMoney1);

        // 如果isNaN，则设置为0
        if (isNaN(discountValue)) {
          row.totalMoney1 = 0;
        } else {
          if (discountValue < 0) {
            row.totalMoney1 = 0;
          } else {
            // 四舍五入到两位小数
            row.totalMoney1 = parseFloat(discountValue.toFixed(2));
          }
        }
      }

      row.purchasePrice1 = (
        row.totalMoney1 /
        (1 + row.taxRate1 / 100) /
        row.totalNum /
        (1 - row.discount1 / 100)
      ).toFixed(2);

      this.calculateRow1(row);
    },
    calculateRow1(row) {
      const discountTaxRateRegex = /^(?:[1-9]?\d{1,2}|100)(?:\.\d{1,2})?$/;

      // 验证和重置购货单价（假设购货单价可以是浮点数）
      const positiveNumberRegex = /^\d+(\.\d{1,2})?$/; // 匹配正数，小数点最多两位
      if (
        !positiveNumberRegex.test(row.purchasePrice1) ||
        row.purchasePrice1 === ""
      ) {
        this.$message({
          showClose: true,
          message: "购货单价必须是正数,且小数点后最多两位",
          type: "warning",
        });
        // 将字符串转换为浮点数
        let discountValue = parseFloat(row.purchasePrice1);
        alert(row.purchasePrice1);
        // 如果isNaN，则设置为0
        if (isNaN(discountValue)) {
          row.purchasePrice1 = 0;
        } else {
          // 修正为0-100之间的值
          if (discountValue < 0) {
            row.purchasePrice1 = 0;
          } else {
            // 四舍五入到两位小数
            row.purchasePrice1 = parseFloat(discountValue.toFixed(2));
          }
        }
      }

      // 验证和重置折扣率和税率
      if (!discountTaxRateRegex.test(row.discount1) || row.discount1 === "") {
        this.$message({
          showClose: true,
          message: "折扣率必须是0-100之间小数点最多两位的数",
          type: "warning",
        });

        // 将字符串转换为浮点数
        let discountValue = parseFloat(row.discount1);

        // 如果isNaN，则设置为0
        if (isNaN(discountValue)) {
          row.discount1 = 0;
        } else {
          // 修正为0-100之间的值
          if (discountValue < 0) {
            row.discount1 = 0;
          } else if (discountValue > 100) {
            row.discount1 = 100;
          } else {
            // 四舍五入到两位小数
            row.discount1 = parseFloat(discountValue.toFixed(2));
          }
        }
      }
      if (!discountTaxRateRegex.test(row.taxRate1) || row.taxRate1 === "") {
        this.$message({
          showClose: true,
          message: "税率必须是0-100之间小数点最多两位的数",
          type: "warning",
        });

        // 将字符串转换为浮点数
        let discountValue = parseFloat(row.taxRate1);

        // 如果isNaN，则设置为0
        if (isNaN(discountValue)) {
          row.taxRate1 = 0;
        } else {
          // 修正为0-100之间的值
          if (discountValue < 0) {
            row.taxRate1 = 0;
          } else if (discountValue > 100) {
            row.taxRate1 = 100;
          } else {
            // 四舍五入到两位小数
            row.taxRate1 = parseFloat(discountValue.toFixed(2));
          }
        }
      }

      // 将字符串转换为浮点数
      row.totalNum = parseInt(row.totalNum, 10);
      row.purchasePrice1 = parseFloat(row.purchasePrice1);
      row.discount1 = parseFloat(row.discount1);
      row.taxRate1 = parseFloat(row.taxRate1);

      // 计算金额
      let amount = (
        row.totalNum *
        row.purchasePrice1 *
        (1 - row.discount1 / 100)
      ).toFixed(2);

      // 计算税额
      let tax = (parseFloat(amount) * (row.taxRate1 / 100)).toFixed(2);

      // 计算价税合计
      row.totalMoney1 = (parseFloat(amount) + parseFloat(tax)).toFixed(2);
    },
    calculateRow3(row) {
      const discountTaxRateRegex = /^(?:[1-9]?\d{1,2}|100)(?:\.\d{1,2})?$/;

      // 验证和重置购货单价（假设购货单价可以是浮点数）
      const positiveNumberRegex = /^\d+(\.\d{1,2})?$/; // 匹配正数，小数点最多两位
      if (
        !positiveNumberRegex.test(row.purchasePrice3) ||
        row.purchasePrice3 === ""
      ) {
        this.$message({
          showClose: true,
          message: "购货单价必须是正数,且小数点后最多两位",
          type: "warning",
        });
        // 将字符串转换为浮点数
        let discountValue = parseFloat(row.purchasePrice3);
        // 如果isNaN，则设置为0
        if (isNaN(discountValue)) {
          row.purchasePrice3 = 0;
        } else {
          // 修正为0-100之间的值
          if (discountValue < 0) {
            row.purchasePrice3 = 0;
          } else {
            // 四舍五入到两位小数
            row.purchasePrice3 = parseFloat(discountValue.toFixed(2));
          }
        }
      }

      // 验证和重置折扣率和税率
      if (!discountTaxRateRegex.test(row.discount3) || row.discount3 === "") {
        this.$message({
          showClose: true,
          message: "折扣率必须是0-100之间小数点最多两位的数",
          type: "warning",
        });

        // 将字符串转换为浮点数
        let discountValue = parseFloat(row.discount3);

        // 如果isNaN，则设置为0
        if (isNaN(discountValue)) {
          row.discount3 = 0;
        } else {
          // 修正为0-100之间的值
          if (discountValue < 0) {
            row.discount3 = 0;
          } else if (discountValue > 100) {
            row.discount3 = 100;
          } else {
            // 四舍五入到两位小数
            row.discount3 = parseFloat(discountValue.toFixed(2));
          }
        }
      }
      if (!discountTaxRateRegex.test(row.taxRate3) || row.taxRate3 === "") {
        this.$message({
          showClose: true,
          message: "税率必须是0-100之间小数点最多两位的数",
          type: "warning",
        });

        // 将字符串转换为浮点数
        let discountValue = parseFloat(row.taxRate3);

        // 如果isNaN，则设置为0
        if (isNaN(discountValue)) {
          row.taxRate3 = 0;
        } else {
          // 修正为0-100之间的值
          if (discountValue < 0) {
            row.taxRate3 = 0;
          } else if (discountValue > 100) {
            row.taxRate3 = 100;
          } else {
            // 四舍五入到两位小数
            row.taxRate3 = parseFloat(discountValue.toFixed(2));
          }
        }
      }

      // 将字符串转换为浮点数
      row.totalNum = parseInt(row.totalNum, 10);
      row.purchasePrice3 = parseFloat(row.purchasePrice3);
      row.discount3 = parseFloat(row.discount3);
      row.taxRate3 = parseFloat(row.taxRate3);

      // 计算金额
      let amount = (
        row.totalNum *
        row.purchasePrice3 *
        (1 - row.discount3 / 100)
      ).toFixed(2);

      // 计算税额
      let tax = (amount * (row.taxRate3 / 100)).toFixed(2);

      // 计算价税合计
      row.totalMoney3 = (parseFloat(amount) + parseFloat(tax)).toFixed(2);
    },
    calculateRow2(row) {
      const discountTaxRateRegex = /^(?:[1-9]?\d{1,2}|100)(?:\.\d{1,2})?$/;

      // 验证和重置购货单价（假设购货单价可以是浮点数）
      const positiveNumberRegex = /^\d+(\.\d{1,2})?$/; // 匹配正数，小数点最多两位
      if (
        !positiveNumberRegex.test(row.purchasePrice2) ||
        row.purchasePrice2 === ""
      ) {
        this.$message({
          showClose: true,
          message: "购货单价必须是正数,且小数点后最多两位",
          type: "warning",
        });
        // 将字符串转换为浮点数
        let discountValue = parseFloat(row.purchasePrice2);
        // 如果isNaN，则设置为0
        if (isNaN(discountValue)) {
          row.purchasePrice2 = 0;
        } else {
          // 修正为0-100之间的值
          if (discountValue < 0) {
            row.purchasePrice2 = 0;
          } else {
            // 四舍五入到两位小数
            row.purchasePrice2 = parseFloat(discountValue.toFixed(2));
          }
        }
      }

      // 验证和重置折扣率和税率
      if (!discountTaxRateRegex.test(row.discount2) || row.discount2 === "") {
        this.$message({
          showClose: true,
          message: "折扣率必须是0-100之间小数点最多两位的数",
          type: "warning",
        });

        // 将字符串转换为浮点数
        let discountValue = parseFloat(row.discount2);

        // 如果isNaN，则设置为0
        if (isNaN(discountValue)) {
          row.discount2 = 0;
        } else {
          // 修正为0-100之间的值
          if (discountValue < 0) {
            row.discount2 = 0;
          } else if (discountValue > 100) {
            row.discount2 = 100;
          } else {
            // 四舍五入到两位小数
            row.discount2 = parseFloat(discountValue.toFixed(2));
          }
        }
      }
      if (!discountTaxRateRegex.test(row.taxRate2) || row.taxRate2 === "") {
        this.$message({
          showClose: true,
          message: "税率必须是0-100之间小数点最多两位的数",
          type: "warning",
        });

        // 将字符串转换为浮点数
        let discountValue = parseFloat(row.taxRate2);

        // 如果isNaN，则设置为0
        if (isNaN(discountValue)) {
          row.taxRate2 = 0;
        } else {
          // 修正为0-100之间的值
          if (discountValue < 0) {
            row.taxRate2 = 0;
          } else if (discountValue > 100) {
            row.taxRate2 = 100;
          } else {
            // 四舍五入到两位小数
            row.taxRate2 = parseFloat(discountValue.toFixed(2));
          }
        }
      }

      // 将字符串转换为浮点数
      row.totalNum = parseInt(row.totalNum, 10);
      row.purchasePrice2 = parseFloat(row.purchasePrice2);
      row.discount2 = parseFloat(row.discount2);
      row.taxRate2 = parseFloat(row.taxRate2);

      // 计算金额
      let amount = (
        row.totalNum *
        row.purchasePrice2 *
        (1 - row.discount2 / 100)
      ).toFixed(2);

      // 计算税额
      let tax = (amount * (row.taxRate2 / 100)).toFixed(2);

      // 计算价税合计
      row.totalMoney2 = (parseFloat(amount) + parseFloat(tax)).toFixed(2);
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      let validData = data.filter((item) => item.goodcode); // 过滤出商品编码不为空的行

      let totalNum = 0; // 用于累计数量的合计
      let totalMoney1 = 0; // 用于累计供应商1价税合计的合计
      let totalMoney2 = 0; // 用于累计供应商2价税合计的合计
      let totalMoney3 = 0; // 用于累计供应商3价税合计的合计

      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        // 定义需要合计的列属性
        const needSumProperties = [
          "totalNum",
          "totalMoney1",
          "totalMoney2",
          "totalMoney3",
        ];
        if (needSumProperties.includes(column.property)) {
          const values = validData.map((item) => Number(item[column.property]));
          const sum = values.reduce((prev, curr) => {
            const value = Number(curr);
            return !isNaN(value) ? prev + value : prev;
          }, 0);
          if (column.property === "totalNum") {
            totalNum = sum; // 累计数量合计
            sums[index] = sum;
          } else if (column.property === "totalMoney1") {
            totalMoney1 = sum; // 累计价税合计
            sums[index] = sum.toFixed(2);
          } else if (column.property === "totalMoney2") {
            totalMoney2 = sum; // 累计价税合计
            sums[index] = sum.toFixed(2);
          } else if (column.property === "totalMoney3") {
            totalMoney3 = sum; // 累计价税合计
            sums[index] = sum.toFixed(2);
          } else {
            // 其他金额列，保留两位小数
            sums[index] = sum.toFixed(2);
          }
        } else {
          sums[index] = "";
        }
      });

      // 将合计的数量和价税合计赋值给purchaseInquiry对象
      this.priceComparison.quantity = totalNum.toFixed(0);
      this.priceComparison.amount1 = totalMoney1.toFixed(2);
      this.priceComparison.amount2 = totalMoney2.toFixed(2);
      this.priceComparison.amount3 = totalMoney3.toFixed(2);

      return sums;
    },
    reduceRow(index) {
      if (this.priComDetail.length > 1) {
        this.priComDetail.splice(index, 1);
      }
    },
    goods(index) {
      this.index = index;
      this.goodsShow = true;
    },
    addRow(index) {
      const newRow = {
        goodcode: "",
        goodname: "",
        purchasePrice1: 0,
        discount1: 0,
        taxRate1: 0,
        totalMoney1: 0,
        purchasePrice2: 0,
        discount2: 0,
        taxRate2: 0,
        totalMoney2: 0,
        purchasePrice3: 0,
        discount3: 0,
        taxRate3: 0,
        totalMoney3: 0,
        radio: "",
        categoryName: "",
        brandName: "",
        unitname: "",
        imagename: "",
        availableStock: "",
        wId: "",
        totalNum: 1,
        packType: "",
      };

      this.priComDetail.splice(index + 1, 0, newRow);
    },
    yes() {
      this.dialogShow = false;
      var list = this.$refs.choosePro.selectionList;
      if (this.flagPro == 1) {
        this.priceComparison.pro1Name = list[0].providerName;
        this.priceComparison.pro1Id = list[0].providerId;
      }
      if (this.flagPro == 2) {
        this.priceComparison.pro2Name = list[0].providerName;
        this.priceComparison.pro2Id = list[0].providerId;
      }
      if (this.flagPro == 3) {
        this.priceComparison.pro3Name = list[0].providerName;
        this.priceComparison.pro3Id = list[0].providerId;
      }
    },
    getPro(flag) {
      this.dialogShow = true;
      this.flagPro = flag;
    },
    selectEm() {
      this.axios({
        url: "/info/employee/listAll",
      }).then((rs) => {
        this.employee = rs.data.list;
      });
    },
    selctSH() {
      // this.axios({
      //   url: "/info/storeHouse/selectAll",
      // }).then((rs) => {
      //   this.storeHouse = rs.data.list;
      // });
      this.axios
        .get("/info/storeHouse/getAllStore", {
          params: {
            cId: 1,
          },
        })
        .then((rs) => {
          this.storeHouse = rs.data.storeList;
        });
    },
    selectById: function () {
      this.axios({
        url: "/purchase/priceComparison/selectById",
        params: {
          id: this.priceComparison.id,
        },
      }).then((rs) => {
        console.log(rs);

        this.jsonObject=rs.data.purchaseInquiry;
        const jsonObject=this.jsonObject

        this.priceComparison = {
          pro1Name: jsonObject.pro1Name,
          pro2Name: jsonObject.pro2Name,
          pro3Name: jsonObject.pro3Name,
          id: jsonObject.id,
          pro1Id: jsonObject.pro1Id,
          pro2Id: jsonObject.pro2Id,
          pro3Id: jsonObject.pro3Id,
          createDate: jsonObject.createDate,
          yid: jsonObject.yid,
          quantity: jsonObject.quantity,
          amount1: jsonObject.amount1,
          amount2: jsonObject.amount2,
          amount3: jsonObject.amount3,
          remark: jsonObject.remark,
          documentNumber: jsonObject.documentNumber,
        };

        // Initialize the priComDetail array
        this.priComDetail = jsonObject.priComDetailList.map((detail) => ({
          goodcode: detail.goodcode,
          goodname: detail.goodname,
          purchasePrice1: detail.purchasePrice1,
          discount1: detail.discount1,
          taxRate1: detail.taxRate1,
          totalMoney1: detail.totalMoney1,
          purchasePrice2: detail.purchasePrice2,
          discount2: detail.discount2,
          taxRate2: detail.taxRate2,
          totalMoney2: detail.totalMoney2,
          purchasePrice3: detail.purchasePrice3,
          discount3: detail.discount3,
          taxRate3: detail.taxRate3,
          totalMoney3: detail.totalMoney3,
          radio: detail.radio || "",
          categoryName: detail.categoryName || "",
          brandName: detail.brandName || "",
          unitname: detail.unitname || "",
          imagename: detail.imagename || "",
          availableStock: detail.availableStock || "",
          wId: detail.wId || "",
          totalNum: detail.totalNum,
          packType: detail.packType || "",
          detailRemark: detail.detailRemark || "",
        }));


      });
    },
  },
  created() {
    this.selectEm();
    this.selctSH();

    this.priceComparison.id = this.$route.query.id;
    if (this.priceComparison.id) {
      this.selectById();
    }
  },
};
</script>

<style scoped>
#order {
  width: 100%;
  height: 100%;
}

.order-top {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  width: calc(100% - 20px);
  padding-left: 20px;
  font-size: 13px;
}

.custom-radio .el-radio__label {
  display: none;
}

.form-group {
  display: flex;
  align-items: center;
  margin-right: 20px; /* 组间距 */
  margin-top: 10px;
}

.el-autocomplete-suggestion__item {
  max-width: 100%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.order-content {
  width: 100%;
}

.spanRed {
  color: rgb(255, 98, 93);
  margin-right: 8px;
}

.el-input,
.el-button {
  font-size: 13px;
}

.el-select,
.el-date-picker {
  margin-left: 10px;
}

/* 合计行整体样式修改开始 */
.el-table /deep/ .el-table__footer-wrapper tbody td {
  background-color: #fff1d4;
}

.el-table /deep/ .el-table__body tr:hover > td {
  background-color: #fff1d4;
}
</style>